/**
 * @description 登录权鉴
 */
import { TOKEN_KEY } from '@/config'
import { getcookiesInServer, getcookiesInClient } from '@/utils/auth'

// 登录成功后禁止访问的路由
const LOGGED_BAN_ENUM = ['user-login', 'user-register', 'user-forget', 'from-platform']

export default function({ route, req, res, redirect, store }) {
  const isClient = process.client
  const isServer = process.server
  let redirectURL = '/user/login'
  let token, routeName, path
  //在服务端
  if (isServer) {
    const cookies = getcookiesInServer(req)
    path = req.originalUrl
    token = cookies[TOKEN_KEY] ? cookies[TOKEN_KEY] : ''
    routeName = route.name
  }
  //在客户端判读是否需要登陆
  if (isClient) {
    token = getcookiesInClient(TOKEN_KEY)
    path = route.path
    routeName = route.name
  }
  if (path) {
    redirectURL = '/user/login?ref=' + encodeURIComponent(path) // 解码用decodeURIComponent
  }
  //需要进行权限判断的页面开头
  if (LOGGED_BAN_ENUM.indexOf(routeName) !== -1) {
    if (token) {
      redirect('/')
    }
  } else {
    if (!token) {
      redirect(redirectURL)
    }
  }
}
